package com.giraffe.common.jpa.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.giraffe.common.security.model.LoginUser;
import com.giraffe.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @Author ldx
 * @Date 2023/02/06 15:52
 **/
@Component
@Slf4j
public class StaffCenterMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {
    try {
      LoginUser loginUser =  SecurityUtils.getLoginUser();
      log.info("======插入拦截添加公共字段,对象信息为{}====", loginUser);
      if (Objects.nonNull(loginUser)) {
        this.setFieldValByName("createAccount", loginUser.getUserid().toString(), metaObject);
        this.setFieldValByName("createName", loginUser.getUsername(), metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("modifyAccount", loginUser.getUserid().toString(), metaObject);
        this.setFieldValByName("modifyName", loginUser.getUsername(), metaObject);
        this.setFieldValByName("modifyTime", new Date(), metaObject);
      }
    } catch (Exception e) {
      log.error("插入拦截发生异常====信息为{}", e.getMessage());
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    try {
      LoginUser loginUser = SecurityUtils.getLoginUser();
      log.info("======插入拦截添加公共字段,对象信息为{}====", loginUser);
      if (Objects.nonNull(loginUser)) {
        this.setFieldValByName("modifyAccount", loginUser.getUserid().toString(), metaObject);
        this.setFieldValByName("modifyName", loginUser.getUsername(), metaObject);
        this.setFieldValByName("modifyTime", new Date(), metaObject);
      }
    } catch (Exception e) {
      log.error("插入拦截发生异常====信息为{}", e.getMessage());
    }
  }
}
